//
// Created by Wesley on 25-1-7.
//

#ifndef STRING_H
#define STRING_H
#include <cstring>
#include <iostream>

class String {
public:
    // explicit，编译器将不允许隐式类型转换，必须显式地调用构造函数。
    explicit String(const char* str = nullptr);

    // copy构造
    String(const String& other);

    // 析构函数,当一个对象的生命周期结束时，析构函数会被自动调用
    ~String() {
        delete[] data;
    }

    // copy赋值
    String& operator=(const String& other);

    char* getData() const { return data; }

private:
    char* data;
};

inline String::String(const char* str) {
    if (str) {
        data = new char[strlen(str) + 1];
        strcpy(data, str);
    } else {
        // 初始化
        data = new char[1];
        *data = '\0';
    }
}

inline String::String(const String& other) {
    data = new char[strlen(other.data) + 1];
    strcpy(data, other.data);
}

inline String& String::operator=(const String& other) {
    if (this != &other) {
        // 清空当前对象存储空间, 再重新赋值
        delete[] data;
        data = new char[strlen(other.data) + 1];
        strcpy(data, other.data);
        return *this;
    }
    return *this;
}


inline std::ostream& operator<<(std::ostream& os, const String& str) {
    return os << str.getData();
}

#endif //STRING_H
